package com.rtzh.learnkotlin.ui

import android.os.Bundle
import android.os.PersistableBundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.rtzh.learnkotlin.R
import com.rtzh.learnkotlin.adapter.MsgAdapter
import com.rtzh.learnkotlin.bean.Msg
import kotlinx.android.synthetic.main.activity_ui_best_practice.*

/**
 * Recyclerview根据type摆放item
 */
class UiBestPracticeActivity : AppCompatActivity(), View.OnClickListener {
    private val msgList = ArrayList<Msg>()
    private var adapter: MsgAdapter? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ui_best_practice)
        initMsg()
        val layoutManager= LinearLayoutManager(this)
        uirecyclerView.layoutManager=layoutManager
        adapter = MsgAdapter(msgList)
        uirecyclerView.adapter = adapter
        send.setOnClickListener(this)
    }

    private fun initMsg() {
        val msg1 = Msg("Hello guy.", Msg.TYPE_RECEIVED)
        msgList.add(msg1)
        val msg2 = Msg("Hello. Who is that?", Msg.TYPE_SENT)
        msgList.add(msg2)
        val msg3 = Msg("This is Tom. Nice talking to you. ", Msg.TYPE_RECEIVED)
        msgList.add(msg3)
    }

    override fun onClick(v: View?) {
        when(v){
            send->{
                val content=inputText.text.toString()
                if (content.isNotEmpty()) {
                    val msg = Msg(content,Msg.TYPE_SENT)
                    msgList.add(msg)
                    adapter?.notifyItemInserted(msgList.size-1)
                    uirecyclerView.scrollToPosition(msgList.size-1)
                    inputText.setText("")
                }
            }
        }
    }


}